<template>
  <div class="DatasetList">
    <el-card style="min-width: 15%;">
      <div style="margin-bottom: 10px;">
        <el-button type="success" :disabled="checkedColumn.length == 0" @click="handleExport">导出Excel</el-button>
      </div>
      <el-tree ref="testTree" :data="data" :props="defaultProps" default-expand-all @node-click="handleNodeClick"
        :highlight-current="true" :current-node-key="1" node-key="label"></el-tree>
    </el-card>
    <el-card style="flex: 1;">
      <div style="margin: 0 10px 20px 10px" v-if="checkedColumn.length > 0">
        <div style="margin-bottom: 20px;">
          <div style="margin-bottom: 10px;font-weight: bold;">请选择需要展示的字段：</div>
          <el-checkbox-group v-model="checkedColumn" :min="0" :max="100" size="medium"
            style="display: flex;flex-wrap: wrap;gap: 10px;" @change="handleChange">
            <el-checkbox v-for="city in columns" :label="city" :key="city">{{ city }}</el-checkbox>
          </el-checkbox-group>
        </div>
        <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item :label="item.label" v-for="(item, index) in searchData" :key="index">
            <el-col :span="22">
              <el-input :rows="5" v-model="searchForm[item.value]" clearable type="text"
                :placeholder="`请输入${item.label}`" />
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="handleRest">重置</el-button>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="tableData" style="width: 100%" v-if="checkedColumn.length > 0">
        <el-table-column type="expand">
          <template slot-scope="props">
            <!-- <el-form label-position="left" inline class="demo-table-expand" label-width="200px">
              <el-form-item :label="item" v-for="(item, index) in columns" :key="index">
                <span>{{ props.row[`col_${index}`] }}</span>
              </el-form-item>
            </el-form> -->
            <el-descriptions class="margin-top" :column="2" :size="size" border>
              <el-descriptions-item label-class-name="my-label" v-for="(item, index) in columns" :key="index">
                <template slot="label">
                  <span class="my-label"> {{ item }}</span>
                </template>
                <el-tag size="small"> {{ props.row[`col_${index}`] }}</el-tag>

              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="item.label" width="auto" :prop="item.value"
          v-for="(item, index) in searchData" :key="index">
        </el-table-column>
        <el-table-column label="操作人" prop="status_update_user_name" width="100" align="center" fixed="right">

        </el-table-column>
        <el-table-column label="当前状态" width="80" align="center"
          :filters="[{ text: '家', value: '家' }, { text: '公司', value: '公司' }]" :filter-method="filterTag"
          filter-placement="bottom-end" fixed="right">

          <template slot-scope="scope">
            <el-tag v-if="scope.row.data_status"> {{ scope.row.data_status }}</el-tag>
            <el-tag type="info" v-else>未使用</el-tag>

          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="100">
          <template slot-scope="scope">
            <el-dropdown>
              <el-button type="primary">
                设置状态<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="新增">
                  <span @click="handleCommand(scope.row, '新增')"
                    style="width: 80px;line-height: 30px; font-size: 15px;text-align: center;  display: inline-block;">新增</span>
                </el-dropdown-item>
                <el-dropdown-item command="不变">
                  <span @click="handleCommand(scope.row, '不变')"
                    style="width: 80px;line-height: 30px; font-size: 15px;text-align: center;  display: inline-block;">不变</span>
                </el-dropdown-item>
                <el-dropdown-item command="下线">
                  <span @click="handleCommand(scope.row, '下线')"
                    style="width: 80px;line-height: 30px; font-size: 15px;text-align: center;  display: inline-block;">下线</span>
                </el-dropdown-item>
                <el-dropdown-item command="调整">
                  <span @click="handleCommand(scope.row, '调整')"
                    style="width: 80px;line-height: 30px; font-size: 15px;text-align: center;  display: inline-block;">调整</span>
                </el-dropdown-item>
                <el-dropdown-item command="重置">
                  <span @click="handleCommand(scope.row, '')"
                    style="width: 80px;line-height: 30px; font-size: 15px;text-align: center;  display: inline-block;">重置</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <!-- <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">使用数据</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页信息 -->
      <div class="pagination-container" v-if="checkedColumn.length > 0">
        <el-pagination background layout="total, prev, pager, next, jumper" @current-change="handlePageChange"
          @size-change="handleSizeChange" :current-page="pageNum" :total="total">
        </el-pagination>
      </div>
      <el-empty description="描述文字" v-if="checkedColumn.length == 0"></el-empty>
      <el-dialog :visible.sync="changeDialog" title="选择较上月调整字段">
        <el-checkbox-group v-model="changeColumn" :min="0" :max="100" size="medium"
          style="display: flex;flex-wrap: wrap;gap: 10px;">
          <el-checkbox border v-for="(city, index) in columns" :label="index + ''" :key="index + ''">{{ city }}</el-checkbox>
        </el-checkbox-group>
        <div class="button-container" style="text-align: center;margin: 20px 0;">
          <el-button type="primary" @click.native.prevent="handleColChange">确认调整</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { Message } from "element-ui";
import List from "../../../views/example/list.vue"
import DatasetApi from "../api/Dataset.js"
import { throttle } from 'lodash';
export default {

  data() {
    return {
      searchForm: {

      },
      total: 100,
      pageSize: 10,
      sheetName: "",
      pageNum: 1,
      // 是否显示添加/编辑对话框
      showEditDialog: false,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label',
        key: 'label',
      },
      tableData: [],
      checkedColumn: [],
      columns: [],
      throttledClick: null,
      searchData: [],
      changeColumn: [],
      changeDialog: false,
      changeId: "",
      changDataId: ""
    }
  },
  methods: {
    handleExport() {
      DatasetApi.exportFiltered().then(res => {
        let date = new Date()
        const elink = document.createElement('a');
        elink.download = `延安${date.getFullYear()}年${date.getMonth() + 1}月社会渠道服务费需求表.xlsx`;
        elink.style.display = 'none';
        const blob = new Blob([res.data], { type: 'application/x-msdownload' });
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      })
    },
    filterTag(value, row) {
      return row.dataStatus === value;
    },
    handleChange(arr) {
      this.searchData = this.getIndices(this.columns, arr)
    },
    handleColChange() {

      let changeCol = this.changeColumn.join(",")
      if (this.changDataId) {
        DatasetApi.updatechangeData({id:this.changDataId,lie: changeCol}).then(res=>{
          DatasetApi.updateDataStatus({
            "sheetName": this.sheetName,
            "rowId": this.changeId,
            "dataStatus": "调整",
            "changId": this.changDataId,
            "updateUser":this.$store.getters.userid
          }).then(res => {
            this.changeDialog = false
            Message.success("设置成功")
            this.getSheetData()
          })
        })
      } else {
        DatasetApi.addchangeData({ biao: this.sheetName, hang: this.changeId + '', lie: changeCol }).then(res => {
          DatasetApi.updateDataStatus({
            "sheetName": this.sheetName,
            "rowId": this.changeId,
            "dataStatus": "调整",
            "changId": res.data.data,
            "updateUser":this.$store.getters.userid
          }).then(res => {
            this.changeDialog = false
            Message.success("设置成功")
            this.getSheetData()
          })
        })
      }

    },
    getIndices(originalArray, newArray) {
      const indices = [];
      for (let item of newArray) {
        const index = originalArray.indexOf(item);
        indices.push({ value: `col_${index}`, label: item, key: index });
      }
      return indices;
    },
    clickHandler(resp) {
      this.sheetName = resp.label
      this.pageNum = 1
      this.handleRest()
      this.getSheetData()
      this.getColumnNames()

    },
    handleNodeClick: throttle(function (...args) {
      const value = this.clickHandler(...args);
    }, 1000),
    handleQuery() {
      this.pageNum = 1
      this.getSheetData()
    },
    handleRest() {
      Object.keys(this.searchForm).forEach(key => {
        this.searchForm[key] = undefined; // 或者 obj[key] = undefined;
      });

    },
    handleAdd() { },
    handleExportExcel() { },
    handleEdit() {

    },


    handleCommand(row, status) {
      if (status === "调整") {
        this.changeColumn = []
        this.changeId = row.id
        if (row.changId) {
          this.changDataId = row.changId
          DatasetApi.getchangedetail({ id: row.changId }).then(res => {
            this.changeColumn = res.data.data.lie.split(",")
          })
        } else {
          this.changDataId = ""
        }

        return this.changeDialog = true
      }
      if (row.changId) {
        DatasetApi.deletechangeData({ id: row.changId })
      }
      DatasetApi.updateDataStatus({
        "sheetName": this.sheetName,
        "rowId": row.id,
        "dataStatus": status,
        "updateUser":status?this.$store.getters.userid:""
      }).then(res => {
        Message.success("设置成功")
        this.getSheetData()
      })
    },
    async getSheetData() {
      let sheetData = await DatasetApi.getSheetData({ sheetName: this.sheetName, pageSize: this.pageSize, pageNum: this.pageNum, ...this.searchForm })
      if (sheetData.data.code != 200) {
        return Message.error("数据获取失败,请上传模板！")
      }
      this.tableData = sheetData.data.data.list
      this.total = sheetData.data.data.total
    },
    async getColumnNames() {
      let columnData = await DatasetApi.getColumnNames(this.sheetName)
      this.columns = columnData.data.data

      this.checkedColumn = this.columns.slice(0, 5)
      this.handleChange(this.checkedColumn)
    },
    async initData() {
      let resData = await DatasetApi.getFileNameAndSheetNames()
      if (resData.data.code == 200) {
        this.data = resData.data.data.sheetNames.map(item => { return { label: item } })
        this.sheetName = resData.data.data.sheetNames[0]
        this.$nextTick(() => {
          this.$refs.testTree.setCurrentKey(resData.data.data.sheetNames[0])
          this.getSheetData()
          this.getColumnNames()
        })

      }
    },
    // 处理翻页事件
    handlePageChange(currentPage) {
      this.pageNum = currentPage
      this.getSheetData()
    },
    // 处理页面总条数事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.getSheetData()
    },
  },
  mounted() {
    this.initData()
    this.throttledClick = throttle(this.handleNodeClick, 5000);
  }
}
</script>
<style>
.DatasetList {
  padding: 20px;
  display: flex;
  gap: 20px;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

::v-deep .el-tree-node:focus>.el-tree-node__content {
  background-color: #6195F0 !important;
  color: #fff !important;
}

/* 节点失焦时的背景颜色 */
::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  background-color: #6195F0 !important;
  color: #fff !important;
}

.el-tree-node__content {
  padding: 20px !important;
}

.my-label {
  font-weight: bold;
  color: #000000;
}
</style>